package com.github.prontera.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.prontera.ApiVersion;
import com.github.prontera.client.BaseRequestListener;
import com.github.prontera.client.DownloadListener;
import com.github.prontera.client.OperationCanceledException;
import com.github.prontera.client.RestRequest;
import com.github.prontera.common.filter.CurrentUserId;
import com.github.prontera.common.filter.IgnoreAuth;
import com.github.prontera.domain.Client;
import com.github.prontera.domain.IssueAnswer;
import com.github.prontera.domain.ZClient;
import com.github.prontera.domain.enums.ClientTypeEnum;
import com.github.prontera.domain.enums.GenderEnum;
import com.github.prontera.model.response.ObjectDataResponse;
import com.github.prontera.service.IssueAnswerService;
import com.github.prontera.service.ZClientService;
import com.github.prontera.util.DateTimeUtil;
import com.github.prontera.util.EncodeUtil;
import com.github.prontera.util.LoopRunnable;
import com.github.prontera.util.URLUtils;

/**
 * 客户端
 */
@RestController
@RequestMapping(value = ApiVersion.API_V1_PREFIX + "/download")
public class DownloadController {

	@Autowired
	private ZClientService zClientService;
	@Autowired
	private IssueAnswerService issueAnswerService;

	private static volatile AtomicInteger pageIndex = new AtomicInteger(1);
	private static volatile AtomicInteger page = new AtomicInteger(1);
	private static volatile AtomicLong time = new AtomicLong(0);

	private void download(Long id, IssueAnswer issueAnswer) {
		String datePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy\\MM\\dd");
		String httpDatePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy/MM/dd");

		String imageIp = "http://image.yuejiulai.com";
		String videoIp = "http://video.yuejiulai.com";

		if (!new File("E:\\media2\\" + datePath + "\\" + id + "\\").exists()) {
			new File("E:\\media2\\" + datePath + "\\" + id + "\\").mkdirs();
		}

		String[] imagePngUrls = issueAnswer.getImage().split("[//]");
		String imageFilename = imagePngUrls[imagePngUrls.length - 1];
		String imagehttpDatePath = imageIp + "/" + httpDatePath + "/" + id + "/" + imageFilename;

		String[] videoPngUrls = issueAnswer.getVideo().split("[//]");
		String videoFilename = videoPngUrls[videoPngUrls.length - 1];
		String videohttpDatePath = videoIp + "/" + httpDatePath + "/" + id + "/" + videoFilename;

		String[] headImagePngUrls = issueAnswer.getHeadImage().split("[//]");
		String headImageFilename = headImagePngUrls[headImagePngUrls.length - 1];
		String headImagehttpDatePath = imageIp + "/" + httpDatePath + "/" + id + "/" + headImageFilename;

		ZClient client = new ZClient();
		client.setId(id);
		client.setHeadImage(headImagehttpDatePath);
		zClientService.update(client);

		RestRequest request = new RestRequest(issueAnswer.getImage());
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.download("E:\\media2\\" + datePath + "\\" + id + "\\" + imageFilename, new DownloadListener() {

			public void onError(Exception ex) {

			}

			public void onProgress(float progress, float total) throws OperationCanceledException {

			}

			@Override
			public void onComplete(Object response) {

			}
		});

		request = new RestRequest(issueAnswer.getVideo());
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.download("E:\\media2\\" + datePath + "\\" + id + "\\" + videoFilename, new DownloadListener() {

			public void onError(Exception ex) {

			}

			public void onProgress(float progress, float total) throws OperationCanceledException {

			}

			@Override
			public void onComplete(Object response) {

			}
		});

		request = new RestRequest(issueAnswer.getHeadImage());
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.download("E:\\media2\\" + datePath + "\\" + id + "\\" + headImageFilename, new DownloadListener() {

			public void onError(Exception ex) {

			}

			public void onProgress(float progress, float total) throws OperationCanceledException {

			}

			@Override
			public void onComplete(Object response) {

			}
		});

		issueAnswer.setVideo(videohttpDatePath);
		issueAnswer.setImage(imagehttpDatePath);
		issueAnswerService.insert(issueAnswer);

	}

	@IgnoreAuth
	@RequestMapping(value = "downVedio", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Boolean> downVedio(@CurrentUserId Long clientId) throws Exception {
		LoopRunnable loopRunnable = new LoopRunnable(new Runnable() {

			@Override
			public void run() {
				startdDwnVedio();
			}
		});
		loopRunnable.setSleepInterval(1000 * 60);
		new java.lang.Thread(loopRunnable).start();
		return new ObjectDataResponse<Boolean>(true);
	}
	
	
	@IgnoreAuth
	@RequestMapping(value = "getUserInfo", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Object> getUserInfo(@RequestBody String uid)  {
		Map<String, String> params = new HashMap<String, String>();
		String uri = URLUtils.append("http://120.25.135.13//api/user/"+uid, params);
		RestRequest request = new RestRequest(uri);
		request.addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		Object objectNode = request.get();
		System.out.println(objectNode);
		
		System.out.println("--------1-----------");
		
		String uri2 = URLUtils.append("http://120.25.135.13/api/user/"+uid+"/videos2?v=2.7.2&dev=android&dev_version=8.0.0&dev_name=DUK-AL20&uuid=ea8fceffc05b242f", params);
		RestRequest request2  = new RestRequest(uri2);
		request2 .addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request2 .addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		
		System.out.println("--------2-----------");
		Object objectNode2  = request2.get();
		System.out.println("|"+objectNode2);
		System.out.println("--------3-----------");
		
		return new ObjectDataResponse<Object>(objectNode);
	}
	
	

	@IgnoreAuth
	@RequestMapping(value = "downAvatar", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Boolean> downAvatar(@CurrentUserId Long clientId) throws Exception {
		startDownAvatar();
		return new ObjectDataResponse<Boolean>(true);
	}
	
	@IgnoreAuth
	@RequestMapping(value = "startDownNikename", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Boolean> startDownNikename(@CurrentUserId Long clientId) throws Exception {
		LoopRunnable loopRunnable = new LoopRunnable(new Runnable() {

			@Override
			public void run() {
				try {
					startDownNikename();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		loopRunnable.setSleepInterval(1000 * 3);
		new java.lang.Thread(loopRunnable).start();
		return new ObjectDataResponse<Boolean>(true);
	}

	private void startDownAvatar() throws InterruptedException {
		ZClient client=	new ZClient();
		client.setPhotosIsNull(true);
		client.setPageIndex(pageIndex.get());
		client.setPageSize(20);
		List<ZClient> fClients=zClientService.find(client);
		for (ZClient client2 : fClients) {
			startDownAvatar(client2.getId(),client2.getUid());
		}
		Thread.sleep(1000);
		startDownAvatar();	
	}
	
	private void startDownNikename() throws InterruptedException {
		ZClient client=	new ZClient();
		client.setPageIndex(pageIndex.get());
		client.setPageSize(20);
		List<ZClient> fClients=zClientService.find(client);
		for (ZClient client2 : fClients) {
			startDownNikename(client2.getId(),client2.getUid());
		}
		pageIndex.set(pageIndex.get()+1);
	}
	
	private void startDownNikename(Long clientId,String uid) {
		Map<String, String> params = new HashMap<String, String>();
		String uri = URLUtils.append("http://120.25.135.13//api/user/"+uid, params);
		RestRequest request = new RestRequest(uri);
		request.addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		request.get(new BaseRequestListener() {
			public void onError(Exception ex) {

			}

			public void onComplete(Object response) {
				String objectNode = (String) response;
				System.out.println(objectNode);
				
				ZClient client = new ZClient();
				JSONObject jsonObject = new JSONObject(objectNode);
				JSONObject userObj = jsonObject.getJSONObject("data");
				String nickname = userObj.optString("nickname");
				Integer height = userObj.optInt("height");
				Integer weight = userObj.optInt("weight");
				Integer gender = userObj.optInt("gender");
				Integer age = userObj.optInt("age");
				Integer score = userObj.optInt("score");
				JSONObject addressObj = userObj.optJSONObject("address");
				if(addressObj!=null){
					String province = addressObj.optString("province");
					String city = addressObj.optString("city");
					List<String> list=new ArrayList<>();
					list.add(province);
					list.add(city);
					if(!StringUtils.isEmpty(province)){
						client.setPermanent(StringUtils.join(list,","));
					}else{
						client.setPermanent("");
					}
				}
				client.setScore(score);
				client.setAge(age);
				client.setHeight(new Double(height));
				client.setWeight(new Double(weight));
				client.setId(clientId);
				
			    String regEx="[a-zA-Z0-9\\u4e00-\\u9fa5]";  
		        Pattern   p   =   Pattern.compile(regEx);     
		        Matcher   m   =   p.matcher(nickname);
		        StringBuffer sb = new StringBuffer();
		        while(m.find()){
		        	sb.append(m.group());
		        }
			    System.out.println(sb);
				
				client.setNickname(sb.toString());
				if(gender!=null&&gender.intValue()==2){
					client.setGender(GenderEnum.FEMALE);
				}else{
					client.setGender(GenderEnum.MALE);
				}
				try {
					zClientService.update(client);
				} catch (Exception e) {
					e.printStackTrace();
					client.setNickname(URLUtils.encodeURL(nickname));
					zClientService.update(client);
				}
			}
		});
	}
	
	private void startDownAvatar(Long clientId,String uid) {
		Map<String, String> params = new HashMap<String, String>();
		String uri = URLUtils.append("http://120.25.135.13//api/user/"+uid, params);
		RestRequest request = new RestRequest(uri);
		request.addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		request.get(new BaseRequestListener() {
			public void onError(Exception ex) {

			}

			public void onComplete(Object response) {
				String objectNode = (String) response;
				System.out.println(objectNode);
				JSONObject jsonObject = new JSONObject(objectNode);
				JSONArray jsonArray = jsonObject.getJSONObject("data").optJSONArray("photos");
				System.out.println(jsonArray.length());
				List<String> avatars=new ArrayList<String>();
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject skObj = jsonArray.getJSONObject(i);
					if (skObj != null) {
						String avatar = skObj.getString("url");
						System.out.println("-----------------------1-----------avatar["+avatar+"]");
						String datePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy\\MM\\dd");
						String httpDatePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy/MM/dd");

						String imageIp = "http://image.yuejiulai.com";

						if (!new File("E:\\media2\\" + datePath + "\\" + clientId + "\\").exists()) {
							new File("E:\\media2\\" + datePath + "\\" + clientId + "\\").mkdirs();
						}

						String[] imagePngUrls = avatar.split("[//]");
						String imageFilename = imagePngUrls[imagePngUrls.length - 1];
						String imagehttpDatePath = imageIp + "/" + httpDatePath + "/" + clientId + "/" + imageFilename;

						System.err.println("E:\\media2\\" + datePath + "\\" + clientId + "\\" + imageFilename);
						
						System.out.println("------------------------2----------avatar["+imagehttpDatePath+"]");
						
						avatars.add(imagehttpDatePath);
						
						RestRequest request = new RestRequest(avatar);
						request.addHeader("User-Agent",
								"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
						request.download("E:\\media2\\" + datePath + "\\" + clientId + "\\" + imageFilename, new DownloadListener() {

							public void onError(Exception ex) {

							}

							public void onProgress(float progress, float total) throws OperationCanceledException {

							}

							@Override
							public void onComplete(Object response) {
								
							}
						});
					}
				}
				
				String pString=StringUtils.join(avatars,",");
				if(!StringUtils.isEmpty(pString)){
					ZClient client = new ZClient();
					client.setId(clientId);
					client.setPhotos(pString);
					try {
						zClientService.update(client);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

	private void startdDwnVedio() {
		Map<String, String> params = new HashMap<String, String>();
		String uri = URLUtils.append("http://120.25.135.13/api/videos?v=2.3.0&dev=android&dev_version=6.0&dev_name=ZTEV0721&type=hot", params);
		if (page.get() > 1) {
			uri = URLUtils.append("http://120.25.135.13/api/videos?v=2.3.0&dev=android&dev_version=6.0&dev_name=ZTEV0722&sort_value1=" + page.get()
					+ "&sort_value2=" + time.get(), params);
		}
		RestRequest request = new RestRequest(uri);
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		request.get(new BaseRequestListener() {
			public void onError(Exception ex) {

			}

			public void onComplete(Object response) {
				String objectNode = (String) response;
				System.out.println(objectNode);
				JSONObject jsonObject = new JSONObject(objectNode);
				JSONArray jsonArray = jsonObject.getJSONArray("data");
				System.out.println(jsonArray.length());
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObj = jsonArray.getJSONObject(i);
					JSONObject skObj = jsonObj.optJSONObject("sk");

					page.set(jsonObj.optInt("sort_value1"));
					time.set(jsonObj.optLong("sort_value2"));
					if (skObj != null) {
						JSONObject userObj = skObj.getJSONObject("user");

						String uid = userObj.getString("uid");
						String nickname = userObj.getString("nickname");
						try {
							nickname = EncodeUtil.urlEncode(nickname);
						} catch (UnsupportedEncodingException e1) {
							e1.printStackTrace();
						}
						String avatar = userObj.getString("avatar");

						ZClient client = zClientService.findOne(new ZClient() {
							private static final long serialVersionUID = 1L;

							{

								setUid(uid);
							}
						});

						if (client == null) {
							client = new ZClient();
							client.setType(ClientTypeEnum.PULL);
							client.setUid(uid);
							System.out.println("--1--nickname----[" + nickname + "]");
							client.setNickname(nickname);
							client.setHeadImage(avatar);
							try {
								zClientService.insert(client);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

						JSONObject videoObj = skObj.getJSONObject("video");

						String content = skObj.optString("content");
						if (content == null) {
							content = skObj.getJSONObject("groups").getString("content");
						}
						System.out.println("------1------content--------------[" + content + "]");
						try {
							content = EncodeUtil.urlEncode(content);
						} catch (UnsupportedEncodingException e1) {
							e1.printStackTrace();
						}

						IssueAnswer findIssueAnswer = new IssueAnswer();
						findIssueAnswer.setVid(skObj.getString("id"));
						if (issueAnswerService.count(findIssueAnswer) > 0) {
							continue;
						}
						IssueAnswer issueAnswer = new IssueAnswer();
						issueAnswer.setType(1);
						issueAnswer.setVid(skObj.getString("id"));
						issueAnswer.setHeadImage(userObj.getString("avatar"));
						issueAnswer.setClientId(client.getId());
						issueAnswer.setImage(videoObj.optString("cover_url"));
						issueAnswer.setIssue(content);
						issueAnswer.setIssureClientId(client.getId());
						issueAnswer.setVideo(videoObj.getString("video_url"));

						download(client.getId(), issueAnswer);
					} else {// 问题
						JSONObject mndObj = jsonObj.optJSONObject("mmd");
						System.out.println("mndObj----" + mndObj);
						JSONObject userObj = mndObj.getJSONObject("to");

						String uid = userObj.getString("uid");
						String nickname = userObj.getString("nickname");
						try {
							System.out.println("----nickname----[" + nickname + "]");
							nickname = EncodeUtil.urlEncode(nickname);
						} catch (UnsupportedEncodingException e1) {
							e1.printStackTrace();
						}
						String avatar = userObj.getString("avatar");

						ZClient client = zClientService.findOne(new ZClient() {
							private static final long serialVersionUID = 1L;

							{

								setUid(uid);
							}
						});

						if (client == null) {
							client = new ZClient();
							client.setType(ClientTypeEnum.PULL);
							client.setUid(uid);
							client.setNickname(nickname);
							client.setHeadImage(avatar);
							try {
								zClientService.insert(client);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

						JSONObject videoObj = mndObj.getJSONArray("answers").getJSONObject(0).getJSONObject("video");
						//
						IssueAnswer findIssueAnswer = new IssueAnswer();
						findIssueAnswer.setVid(mndObj.getString("id"));
						if (issueAnswerService.count(findIssueAnswer) > 0) {
							continue;
						}
						String content = mndObj.getString("content");
						System.out.println("------2------content--------------[" + content + "]");
						try {
							content = EncodeUtil.urlEncode(content);
						} catch (UnsupportedEncodingException e1) {
							e1.printStackTrace();
						}

						IssueAnswer issueAnswer = new IssueAnswer();
						issueAnswer.setVid(mndObj.getString("id"));
						issueAnswer.setHeadImage(userObj.getString("avatar"));
						issueAnswer.setType(1);
						issueAnswer.setClientId(client.getId());
						issueAnswer.setImage(jsonObj.optString("cover_url"));
						issueAnswer.setIssue(content);
						issueAnswer.setIssureClientId(client.getId());
						issueAnswer.setVideo(videoObj.getString("video_url"));

						download(client.getId(), issueAnswer);
					}
				}
			}
		});
	}

}
